<?php
/**
 * 微信js类
 */
class JssdkLogic 
{
 
  private $appId;
  private $appSecret;

  public function __construct($appId,$appSecret) {
    $this->appId = $appId;
    $this->appSecret = $appSecret;
  }
  // 签名
  public function getSignPackage($url='') {
    $jsapiTicket = $this->getJsApiTicket();

    // 注意 URL 一定要动态获取，不能 hardcode.
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $url = empty($url) ? "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" : $url;

    $timestamp = time();
    $nonceStr = $this->createNonceStr();

    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

    $signature = sha1($string);

    $signPackage = array(
      "appId"     => $this->appId,
      "nonceStr"  => $nonceStr,
      "timestamp" => $timestamp,
      "url"       => $url,
      "rawString" => $string,
      "signature" => $signature
      
    );
    return $signPackage; 
  }
// 随机字符串
  private function createNonceStr($length = 16) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
  }


    /**
     * 根据 access_token 获取 ticket
     * @return type
     */
    public function getJsApiTicket(){        
        
        // $ticket = S('ticket');
        // if(!empty($ticket))
        //     return $ticket;
        
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
        $return = $this->httpRequest($url,'GET');
        $return = json_decode($return,1);     
        //S('ticket',$return['ticket'],7000);
        return $return['ticket'];
    }     
      
  
    /**
     * 获取 网页授权登录access token
     * @return type
     */
    public function getAccessToken(){
        //判断是否过了缓存期
        // $access_token = S('access_token');
        // if(!empty($access_token))
        //     return $access_token;
        
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
        $return = $this->httpRequest($url,'GET');
        $return = json_decode($return,1);
        //S('access_token',$return['access_token'],7000);        
        return $return['access_token'];
    }    
    
    // 获取一般的 access_token
    public function get_access_token(){
        //判断是否过了缓存期
        // $wechat = M('wx_user')->find();
        // $expire_time = $wechat['web_expires'];
        // if($expire_time > time()){
        //    return $wechat['web_access_token'];
        // }
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
        $return = $this->httpRequest($url,'GET');
        $return = json_decode($return,1);
        //$web_expires = time() + 7000; // 提前200秒过期
        //M('wx_user')->where(array('id'=>$wechat['id']))->save(array('web_access_token'=>$return['access_token'],'web_expires'=>$web_expires));
        return $return['access_token'];
    }
	
	
	/**
	 * CURL请求
	 * @param $url 请求url地址
	 * @param $method 请求方法 get post
	 * @param null $postfields post数据数组
	 * @param array $headers 请求header信息
	 * @param bool|false $debug  调试开启 默认false
	 * @return mixed
	 */
	function httpRequest($url, $method="GET", $postfields = null, $headers = array(), $debug = false) {
	    $method = strtoupper($method);
	    $ci = curl_init();
	    /* Curl settings */
	    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
	    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
	    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
	    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
	    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
	    switch ($method) {
	        case "POST":
	            curl_setopt($ci, CURLOPT_POST, true);
	            if (!empty($postfields)) {
	                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
	                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
	            }
	            break;
	        default:
	            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
	            break;
	    }
	    $ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
	    curl_setopt($ci, CURLOPT_URL, $url);
	    if($ssl){
	        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
	        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
	    }
	    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
	    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
	    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
	    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
	    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
	    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
	    $response = curl_exec($ci);
	    $requestinfo = curl_getinfo($ci);
	    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
	    if ($debug) {
	        echo "=====post data======\r\n";
	        var_dump($postfields);
	        echo "=====info===== \r\n";
	        print_r($requestinfo);
	        echo "=====response=====\r\n";
	        print_r($response);
	    }
	    curl_close($ci);
	    return $response;
		//return array($http_code, $response,$requestinfo);
	}
    
    /*
     * 向用户推送消息
     */
    public function push_msg($openid,$content){
        $access_token = $this->get_access_token();
        $url ="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}";        
        $post_arr = array(
                        'touser'=>$openid,
                        'msgtype'=>'text',
                        'text'=>array(
                                'content'=>$content,
                            )
                        );
        $post_str = json_encode($post_arr,JSON_UNESCAPED_UNICODE);        
        $return = $this->httpRequest($url,'POST',$post_str);
        $return = json_decode($return,true);        
    }
 
    public function send_template_message($order){
    	$access_token = $this->get_access_token();
    	$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";
    	$open_id = M('users')->where(array('user_id'=>$order['user_id']))->getField('openid');
    	error_log($open_id.date('Ymd H:i:s'),3,'test.log');
    	if(!empty($open_id)){
    		$tempalte = array(
    				'touser'=>$open_id,
    				'template_id'=>'GiApFXcJXrxslu-_0S3Ynn56NP3emHVttcAieUfDEog',
    				'url' => SITE_URL.'/mobile', //点击后跳转地址
    				'topcolor'=>'#7B68EE',
    				'data' => array(
    						'first'  => array('value'=>urlencode("您好，您的订单已支付成功"),'color'=>'#743A3A'),
    						'product'=> array('value'=>urlencode($order['goods_name']),'color'=>"#173177"),
    						'price'  => array('value'=>urlencode($order['total_amount']."元"),'color'=>"#173177"),
    						'time'   => array('value'=>urlencode(date("Y年m月d日  H:i:s")),'color'=>"#173177"),
    						'remark' => array('value'=>urlencode("您的订单已提交，我们将尽快发货。祝您生活愉快"),'color'=>"#173177"),
    				));
    		$json_template = json_encode($tempalte);
    		$res = $this->httpRequest($url,'post',urldecode($json_template));
    		return json_decode($res,true);
    	}
    }
}